<template>
	<div class="form-item-checkbox">
		<!-- 只读展示：统一用普通 field 展示已选文本 -->
		<van-field v-if="readonly" :label="label" :required="required" :readonly="true" :model-value="displayText || '-'" />
		<!-- 可交互模式 -->
		<van-field v-else :name="itemKey" :label="label" :required="required" :disabled="disabled">
			<template #input>
				<!-- radio 类型 -->
				<template v-if="isRadio">
					<div class="radio-wrap">
						<van-radio-group :model-value="modelValue" direction="horizontal" @update:model-value="handleRadioChange">
							<van-radio v-for="item in optionList" :key="item.value" :name="item.value" :disabled="disabled" shape="dot">{{ item.text }}</van-radio>
						</van-radio-group>
					</div>
				</template>
				<!-- checkbox 类型 -->
				<template v-else>
					<van-checkbox-group :model-value="modelValue" direction="horizontal" @update:model-value="handleChange">
						<van-checkbox v-for="item in optionList" :key="item.value" :name="item.value" :disabled="disabled" shape="square">
							{{ item.text }}
						</van-checkbox>
					</van-checkbox-group>
				</template>
			</template>
		</van-field>
	</div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { getDic } from '../../api/index'

export default {
	name: 'FormItemCheckbox',
	props: {
		required: {
			type: Boolean,
			default: false,
		},
		isView: {
			type: Boolean,
			default: false,
		},
		itemKey: {
			type: String,
			default: '',
		},
		modelValue: {
			// 对于 radio 模式下为字符串；checkbox 模式下为数组
			type: [Array, String],
			default: () => [],
		},
		optionList: {
			type: Array,
			default: () => [],
		},
		label: {
			type: String,
			default: '',
		},
		disabled: { type: Boolean, default: false },
		readonly: { type: Boolean, default: false },
		type: { type: String, default: 'checkbox' }, // 'checkbox' | 'radio'
		dicKey: {
			type: String,
			default: '',
		},
	},
	emits: ['update:modelValue', 'change'],
	setup(props, { emit }) {
		const optionList = ref([...props.optionList])
		const isRadio = computed(() => props.type === 'radio')
		// 只读展示的文本：radio 单值直接匹配；checkbox 多值 join
		const displayText = computed(() => {
			if (!optionList.value.length) return ''
			if (isRadio.value) {
				const found = optionList.value.find((o) => o.value === props.modelValue)
				return found ? found.text : ''
			}
			if (Array.isArray(props.modelValue)) {
				return optionList.value
					.filter((o) => props.modelValue.includes(o.value))
					.map((o) => o.text)
					.join('、')
			}
			return ''
		})

		// 初始化字典数据
		const initDic = async () => {
			if (!props.dicKey) return

			try {
				const data = await getDic(props.dicKey)
				console.log(`字典${props.dicKey}原始数据:`, data)

				optionList.value = data.map((item) => ({
					text: item.dictLabel, // 显示文本使用dictLabel
					value: item.dictValue, // 值使用dictValue
				}))
				//更新显示文本
				console.log(`字典${props.dicKey}处理后选项:`, optionList.value)
				// displayText 为 computed，不直接赋值；computed 会基于 optionList 和 modelValue 计算
			} catch (error) {
				console.error('获取字典数据失败:', error)
			}
		}

		// 处理值变化
		const handleChange = (value) => {
			console.log(`FormItemCheckbox[${props.itemKey}] checkbox值变化:`, value)
			emit('update:modelValue', value)
			emit('change', { [props.itemKey]: value })
		}
		const handleRadioChange = (val) => {
			console.log(`FormItemCheckbox[${props.itemKey}] radio值变化:`, val)
			emit('update:modelValue', val)
			emit('change', { [props.itemKey]: val })
		}

		onMounted(() => {
			initDic()
		})

		return {
			optionList,
			handleChange,
			handleRadioChange,
			isRadio,
			readonly: props.readonly,
			displayText,
		}
	},
}
</script>

<style lang="less" scoped>
.form-item-checkbox {
	:deep(.van-field__label) {
		width: 100px;
	}

	:deep(.van-checkbox-group) {
		display: flex;
		flex-wrap: wrap;
		gap: 8px;

		.van-checkbox {
			margin-right: 16px;
			margin-bottom: 8px;
		}
	}
}
</style>